package com.zrc.superframe_tbs

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.blankj.utilcode.util.FileUtils
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsReaderView
import org.json.JSONObject
import java.io.File
import java.util.*

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:自定义文件打开阅读View
 */
class FileReaderView @JvmOverloads constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr), TbsReaderView.ReaderCallback{

    var mTbsReaderView: TbsReaderView = TbsReaderView(context, this)

    override fun onFinishInflate() {
        super.onFinishInflate()
        this.addView(mTbsReaderView, LinearLayout.LayoutParams(-1, -1))
    }

    override fun onCallBackAction(integer: Int, o: Any, o1: Any) {

    }

    fun onStop() {
        mTbsReaderView.onStop()//显示文件的界面，退出界面以后需要销毁，否则再次加载文件无法加载成功，会一直显示加载文件进度条。
    }

    @SuppressLint("LogNotTimber")
    fun show(file: File) {//显示文件
        val localBundle = Bundle()//加载文件
        val filePath=file.absolutePath
        val fileName=FileUtils.getFileName(file)
        val tempPath=filePath.replace(fileName, "")
        localBundle.putString("filePath", filePath)
        localBundle.putString("tempPath", tempPath)
        //预加载 返回false表示不支持阅读只能QbSdk打开
        val bool = mTbsReaderView.preOpen(TbsUtils.get().getFileType(file), false)
        if (bool) {
            try {
                mTbsReaderView.openFile(localBundle)
            }catch (e:Exception){

            }
        }else{//使用QbSdk打开
            val params = HashMap<String, String>()
            params["local"] = "true"
            params["entryId"] = "2"
            params["allowAutoDestory"] = "true"
            val objects = JSONObject()
            objects.put("pkgName", context.packageName)
            params["menuData"] = objects.toString()
            QbSdk.getMiniQBVersion(context)
            QbSdk.openFileReader(context, file.absolutePath, params, null)
        }
    }
}